package ynu.edu.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import ynu.edu.entity.Cart;
import ynu.edu.entity.User;
import ynu.edu.repository.CartRepository;
import ynu.edu.repository.UserRepository;

import java.util.List;

@Slf4j
@Service
public class CartService {

    @Autowired
    private CartRepository cartRepository;

    @Autowired
    private UserRepository userRepository;

    private User getUserByName(String userName) {
        return userRepository.findByUserName(userName)
                .orElseThrow(() -> new RuntimeException("用户不存在"));
    }

    public List<Cart> listCartByUserName(String userName) {
        User user = getUserByName(userName);
        return cartRepository.findByUserId(user.getUserId());
    }

    public List<Cart> listCartByUserNameAndBusinessId(String userName, Integer businessId) {
        User user = getUserByName(userName);
        return cartRepository.findByUserIdAndBusinessId(user.getUserId(), businessId);
    }

    @Transactional
    public boolean saveCart(Cart cart) {
        try {
            User user = getUserByName(cart.getUserName());
            cart.setUserId(user.getUserId());
            cartRepository.save(cart);
            return true;
        } catch (Exception e) {
            log.error("Failed to save cart", e);
            return false;
        }
    }

    @Transactional
    public int updateCart(Cart cart) {
        User user = getUserByName(cart.getUserName());
        return cartRepository.updateQuantity(user.getUserId(), 
                                          cart.getBusinessId(), 
                                          cart.getFoodId(), 
                                          cart.getQuantity());
    }

    @Transactional
    public int removeCartItem(Cart cart) {
        User user = getUserByName(cart.getUserName());
        return cartRepository.deleteByUserIdAndBusinessIdAndFoodId(
                user.getUserId(), cart.getBusinessId(), cart.getFoodId());
    }

    @Transactional
    public int removeCartByBusiness(Cart cart) {
        User user = getUserByName(cart.getUserName());
        return cartRepository.deleteByUserIdAndBusinessId(
                user.getUserId(), cart.getBusinessId());
    }
} 